import request from '@/utils/request'

// 证书模板服务基础API路径
const baseUrl = '/qep/certificate/template'

// 模拟数据 - 证书模板列表
const mockTemplates = [
  {
    id: 1,
    name: '质量证明书模板A',
    type: 'quality_certificate',
    description: '标准质量证明书模板，适用于一般产品',
    fileName: 'quality_certificate_template_a.docx',
    filePath: '/certificate_templates/quality_certificate_template_a.docx',
    status: '启用',
    createTime: '2023-09-01',
    updateTime: '2023-09-15'
  },
  {
    id: 2,
    name: '合格证模板B',
    type: 'conformity_certificate',
    description: '标准合格证模板，适用于所有产品',
    fileName: 'conformity_certificate_template_b.docx',
    filePath: '/certificate_templates/conformity_certificate_template_b.docx',
    status: '启用',
    createTime: '2023-09-05',
    updateTime: '2023-09-20'
  },
  {
    id: 3,
    name: '检验报告模板C',
    type: 'inspection_report',
    description: '详细检验报告模板，包含全面检测数据',
    fileName: 'inspection_report_template_c.docx',
    filePath: '/certificate_templates/inspection_report_template_c.docx',
    status: '启用',
    createTime: '2023-10-01',
    updateTime: '2023-10-15'
  }
];

// 获取证书模板列表
export function listTemplate(query) {
  console.log('Mock API: listTemplate', query);
  
  // 使用模拟数据
  let filteredTemplates = [...mockTemplates];
  
  // 应用筛选条件
  if (query) {
    if (query.name) {
      filteredTemplates = filteredTemplates.filter(template => 
        template.name.toLowerCase().includes(query.name.toLowerCase()));
    }
    if (query.type) {
      filteredTemplates = filteredTemplates.filter(template => 
        template.type === query.type);
    }
    if (query.status) {
      filteredTemplates = filteredTemplates.filter(template => 
        template.status === query.status);
    }
  }
  
  // 处理分页
  const pageSize = query.pageSize || 10;
  const pageNum = query.pageNum || 1;
  const startIndex = (pageNum - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const pagedTemplates = filteredTemplates.slice(startIndex, endIndex);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    total: filteredTemplates.length,
    rows: pagedTemplates
  });
}

// 获取证书模板详情
export function getTemplate(id) {
  console.log('Mock API: getTemplate', id);
  const template = mockTemplates.find(template => template.id === parseInt(id));
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: template
  });
}

// 新增证书模板
export function addTemplate(data) {
  console.log('Mock API: addTemplate', data);
  // 创建新模板
  const newId = Math.max(...mockTemplates.map(template => template.id)) + 1;
  const now = new Date().toISOString().split('T')[0];
  const newTemplate = {
    ...data,
    id: newId,
    filePath: data.filePath || `/certificate_templates/${data.fileName || 'new_template.docx'}`,
    status: data.status || '启用',
    createTime: now,
    updateTime: now
  };
  
  mockTemplates.push(newTemplate);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: newTemplate
  });
}

// 修改证书模板
export function updateTemplate(data) {
  console.log('Mock API: updateTemplate', data);
  const index = mockTemplates.findIndex(template => template.id === data.id);
  if (index !== -1) {
    const now = new Date().toISOString().split('T')[0];
    mockTemplates[index] = { 
      ...mockTemplates[index], 
      ...data,
      updateTime: now
    };
  }
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 删除证书模板
export function delTemplate(id) {
  console.log('Mock API: delTemplate', id);
  const index = mockTemplates.findIndex(template => template.id === parseInt(id));
  if (index !== -1) {
    mockTemplates.splice(index, 1);
  }
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 上传证书模板文件
export function uploadTemplateFile(data) {
  console.log('Mock API: uploadTemplateFile', data);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    fileName: data.get('file').name,
    filePath: `/certificate_templates/${data.get('file').name}`,
    url: `/certificate_templates/${data.get('file').name}`
  });
}

// 预览证书模板
export function previewTemplate(id, data) {
  console.log('Mock API: previewTemplate', id, data);
  
  // 创建一个简单的PDF blob (实际应用中这里会返回真实的PDF数据)
  const pdfContent = `%PDF-1.5
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /Resources 4 0 R /MediaBox [0 0 612 792] /Contents 6 0 R >>
endobj
4 0 obj
<< /Font << /F1 5 0 R >> >>
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
6 0 obj
<< /Length 68 >>
stream
BT
/F1 24 Tf
100 700 Td
(Template Preview: Template ID ${id}) Tj
ET
endstream
endobj
xref
0 7
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000216 00000 n
0000000259 00000 n
0000000326 00000 n
trailer
<< /Size 7 /Root 1 0 R >>
startxref
444
%%EOF`;
  
  const blob = new Blob([pdfContent], { type: 'application/pdf' });
  return Promise.resolve(blob);
}

// 获取模板变量列表
export function listTemplateVariables(templateId) {
  console.log('Mock API: listTemplateVariables', templateId);
  
  // 根据模板ID返回不同的变量
  let variables = [];
  
  if (templateId === 1) {
    variables = [
      { id: 1, name: 'productName', description: '产品名称', type: 'text', defaultValue: '' },
      { id: 2, name: 'batchNo', description: '批次号', type: 'text', defaultValue: '' },
      { id: 3, name: 'inspectionDate', description: '检验日期', type: 'date', defaultValue: '' },
      { id: 4, name: 'qualityLevel', description: '质量等级', type: 'select', defaultValue: 'A', options: 'A,B,C,D' }
    ];
  } else if (templateId === 2) {
    variables = [
      { id: 5, name: 'productName', description: '产品名称', type: 'text', defaultValue: '' },
      { id: 6, name: 'batchNo', description: '批次号', type: 'text', defaultValue: '' },
      { id: 7, name: 'manufactureDate', description: '生产日期', type: 'date', defaultValue: '' },
      { id: 8, name: 'inspector', description: '检验员', type: 'text', defaultValue: '' }
    ];
  } else if (templateId === 3) {
    variables = [
      { id: 9, name: 'productName', description: '产品名称', type: 'text', defaultValue: '' },
      { id: 10, name: 'batchNo', description: '批次号', type: 'text', defaultValue: '' },
      { id: 11, name: 'testResults', description: '测试结果', type: 'textarea', defaultValue: '' },
      { id: 12, name: 'conclusion', description: '结论', type: 'select', defaultValue: '合格', options: '合格,不合格,待定' }
    ];
  }
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: variables
  });
}

// 保存模板变量
export function saveTemplateVariables(variables) {
  console.log('Mock API: saveTemplateVariables', variables);
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 获取Word模板内容
export function getWordContent(id) {
  console.log('Mock API: getWordContent', id);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: {
      content: '<p>这是模板内容示例</p><p>产品名称: {{productName}}</p><p>批次号: {{batchNo}}</p>'
    }
  });
}

// 保存Word模板内容
export function saveWordContent(data) {
  console.log('Mock API: saveWordContent', data);
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 导出为PDF
export function exportToPdf(id, variables) {
  console.log('Mock API: exportToPdf', id, variables);
  
  // 创建一个简单的PDF blob
  const pdfContent = `%PDF-1.5
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /Resources 4 0 R /MediaBox [0 0 612 792] /Contents 6 0 R >>
endobj
4 0 obj
<< /Font << /F1 5 0 R >> >>
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
6 0 obj
<< /Length 68 >>
stream
BT
/F1 24 Tf
100 700 Td
(Exported PDF: Template ID ${id}) Tj
ET
endstream
endobj
xref
0 7
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000216 00000 n
0000000259 00000 n
0000000326 00000 n
trailer
<< /Size 7 /Root 1 0 R >>
startxref
444
%%EOF`;
  
  const blob = new Blob([pdfContent], { type: 'application/pdf' });
  return Promise.resolve(blob);
}

// 解析Word文档
export function parseWord(file) {
  console.log('Mock API: parseWord', file);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: {
      content: '<p>这是解析的Word内容</p>',
      variables: ['productName', 'batchNo', 'inspectionDate']
    }
  });
}

// 解析Excel文档
export function parseExcel(file) {
  console.log('Mock API: parseExcel', file);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: {
      content: '<table><tr><td>产品名称</td><td>批次号</td></tr><tr><td>{{productName}}</td><td>{{batchNo}}</td></tr></table>',
      variables: ['productName', 'batchNo']
    }
  });
}

// 解析PowerPoint文档
export function parsePpt(file) {
  console.log('Mock API: parsePpt', file);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: {
      content: '<div>这是解析的PPT内容</div>',
      variables: ['title', 'content']
    }
  });
}

// 解析PDF文档
export function parsePdf(file) {
  console.log('Mock API: parsePdf', file);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: {
      content: '<div>这是解析的PDF内容</div>',
      variables: []
    }
  });
}

// 通用文件上传接口
export function uploadFile(file) {
  console.log('Mock API: uploadFile', file);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    fileName: file.name,
    filePath: `/uploads/${file.name}`,
    url: `/uploads/${file.name}`
  });
}

// 图片上传接口
export function uploadImage(file) {
  console.log('Mock API: uploadImage', file);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    fileName: file.name,
    filePath: `/uploads/images/${file.name}`,
    url: `/uploads/images/${file.name}`
  });
}

// WordPaster专用上传接口
export function wordpasterUpload(file) {
  console.log('Mock API: wordpasterUpload', file);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    fileName: file.name,
    filePath: `/uploads/wordpaster/${file.name}`,
    url: `/uploads/wordpaster/${file.name}`
  });
}

// 替换DOCX模板文件
export function replaceDocxTemplate(templateId, file) {
  console.log('Mock API: replaceDocxTemplate', templateId, file);
  
  const index = mockTemplates.findIndex(template => template.id === parseInt(templateId));
  if (index !== -1) {
    mockTemplates[index].fileName = file.name;
    mockTemplates[index].filePath = `/certificate_templates/${file.name}`;
    mockTemplates[index].updateTime = new Date().toISOString().split('T')[0];
  }
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 下载模板文件
export function downloadTemplateFile(id) {
  console.log('Mock API: downloadTemplateFile', id);
  
  // 创建一个简单的DOCX blob (实际应用中这里会返回真实的DOCX数据)
  const docxContent = 'This is a mock DOCX file content';
  const blob = new Blob([docxContent], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
  return Promise.resolve(blob);
} 